import React, { useEffect, useState } from 'react';
import { Table, Space, Switch, Input, Button, Popconfirm, Form, InputNumber,Row, Divider, message } from 'antd';
import {  SearchOutlined, ReloadOutlined,  EditOutlined, DeleteOutlined } from '@ant-design/icons';


export interface EditableTableProps {
    name: string;
    getUrl: string;
    postUrl: string;
    putUrl: string;
    deleteUrl: string;
  }

  const EditableCell = ({
    editing,
    dataIndex,
    title,
    inputType,
    record,
    index,
    children,
    ...restProps
  }) => {
    const inputNode =
      inputType === 'switch' ? (
        <Form.Item name={dataIndex} valuePropName="checked" noStyle>
          <Switch checked={record[dataIndex]} />
        </Form.Item>
      ) : (
        <Form.Item name={dataIndex} style={{ margin: 0 }}>
          <Input />
        </Form.Item>
      );
  
    return (
      <td {...restProps}>
        {editing ? inputNode : children}
      </td>
    );
  };
  
const EditableTable:React.FC<EditableTableProps> = function({name,getUrl,postUrl,putUrl,deleteUrl,...otherProps}){
  //console.log()
  //const {TextArea} = Input;
  const [updateForm] = Form.useForm();
  const [insertForm] = Form.useForm();
  const [searchTerm, setSearchTerm] = React.useState("");
  const [messageApi, contextHolder] = message.useMessage();
  const [data, setData] = useState([
  ]);
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 5; // 每页显示5条数据


  const getWarehouse = () =>{
    fetch(getUrl)
    .then(response => response.json())
    .then(data => {
      console.log(data);
      setData(data);
    })
  }
  const updateWarehouse = (row) => {
    fetch(putUrl, {
      method: 'PUT',
      headers: {
          'Content-Type': 'application/json'
      },
      body: JSON.stringify(
         row
      )
  })
  .then(response => response.json())
  .then(data => {if(data.code === '0'){
    messageApi.open({
      type: 'success',
      content: '修改成功',
    });
  }})}
  const deleteWarehouse = (code) => {
    fetch(deleteUrl + code,{
      method: 'DELETE',
    }).then(response => response.json())
      .then(data => {
        if(data.code === '0'){
          messageApi.open({
            type: 'success',
            content: '删除成功',
          });
        }
      })
  }
  useEffect(()=>{
   getWarehouse();
  },[])
  const handleSearch = () => {
    // 假设我们做一个简单的搜索，只搜索 `code` 或 `name` 字段
    const filteredData = data.filter(
      (item) =>
        item.code.includes(searchTerm) || item.name.includes(searchTerm)
    );
    setData(filteredData);
  };

  const resetSearch = () => {
    setSearchTerm("");
    // 这里恢复初始数据
    getWarehouse();
  };

  const [editingKey, setEditingKey] = useState('');

  const onFinish = (values: any) => {
    console.log('Success:', values);
    fetch(postUrl, {
      method: 'POST',
      headers: {
          'Content-Type': 'application/json'
      },
      body: JSON.stringify(
         values
      )
  })
  .then(response => response.json())
  .then(data => {if(data.code === '0'){
    messageApi.open({
      type: 'success',
      content: '新增成功',
    });
    insertForm.resetFields();
  }
  getWarehouse();

})
  .catch(error => console.error('Error:', error));
  };

  const isEditing = (record) => record.id === editingKey;

  const columns = [
    {
      title: '仓库编号',
      dataIndex: 'code',
      key: 'code',
      render: (text, record) => (
        <a style={{ color: '#1890ff' }} onClick={() => edit(record)}>
          {text}
        </a>
      ),
      editable: true
    },
    {
      title: '仓库名称',
      dataIndex: 'name',
      key: 'name',
      editable: true,
    },
    {
      title: '位置',
      dataIndex: 'location',
      key: 'location',
      editable: true,
    },
    {
      title: '面积',
      dataIndex: 'area',
      key: 'area',
      editable: true,
    },
    {
      title: '负责人',
      dataIndex: 'person',
      key: 'person',
      editable: true,
    },
    {
      title: '是否冻结',
      dataIndex: 'frozen',
      key: 'frozen',
      render: (text, record) => <Switch checked={record.frozen}  disabled={!isEditing(record)}/>,
      editable: true,
    },
    {
      title: '备注',
      dataIndex: 'note',
      key: 'note',
      editable: true,
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => {
        return (
          <Space size="middle">
            {isEditing(record) ? (
              <>
                <Button type="link" onClick={() => save(record.id)}>保存</Button>
                <Popconfirm title="确定要取消吗？" onConfirm={cancel}>
                  <Button type="link">取消</Button>
                </Popconfirm>
              </>
            ) : (
              <>
                <a href="#" onClick={() => edit(record)}><EditOutlined /> 修改</a>
                <Popconfirm title="确定要删除吗？" onConfirm={() => deleteRow(record.id)}>
                  <a href="#" style={{ color: 'red' }}><DeleteOutlined /> 删除</a>
                </Popconfirm>
              </>
            )}
          </Space>
        );
      },
    },
  ];

  const edit = (record) => {
    updateForm.setFieldsValue({
      code: '',
      name: '',
      location: '',
      area: '',
      person: '',
      frozen: false,
      note: '',
      ...record,
    });
    setEditingKey(record.id);
  };

  const cancel = () => {
    setEditingKey('');
  };

  const save = async (key) => {
    try {
      const row = await updateForm.validateFields();
      console.log("update row:",row);
      const newData = [...data];
      const index = newData.findIndex((item) => key === item.id);

      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, { ...item, ...row });
        setData(newData);
        setEditingKey('');
        updateWarehouse(row);
      }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };

  const deleteRow = (key) => {
    const newData = data.filter((item) => item.id !== key);
    setData(newData);
    deleteWarehouse(data.find((item) => item.id === key).code);
  };

  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }

    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: col.dataIndex === 'frozen' ? 'switch' : 'text',
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
        onSave: save,
      }),
    };
  });

  return (
    <>
    {/* 搜索框区域 */}
    {contextHolder}
    <Row>
         <Space style={{ marginBottom: 16 , marginTop: 20,marginLeft: 20}}>
        <Input
          placeholder="请输入仓库编号或名称"
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          style={{ width: 200 }}
        />
        <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
          搜索
        </Button>
        <Button icon={<ReloadOutlined />} onClick={resetSearch}>
          重置
        </Button>
        
        
       
      </Space>
      </Row>
      <Divider />
      <Row>
        <Space style={{ marginBottom: 16 , marginTop: 20,marginLeft: 20}}>
        
        <Form form={insertForm} name="InsertForm" layout="inline" onFinish={onFinish}>
          <Form.Item name="code">
            <Input placeholder="仓库编号"/>
          </Form.Item>
          <Form.Item name="name">
            <Input placeholder="仓库名称"/>
          </Form.Item>  
          <Form.Item name="location">
            <Input placeholder="仓库地址" />
          </Form.Item>
          <Form.Item name="area">
            <InputNumber placeholder="仓库面积" />
          </Form.Item>
          <Form.Item name="note">
            <Input.TextArea rows={2} placeholder="备注" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" >+ 新增</Button>
          </Form.Item>
        </Form>
      </Space>
      </Row>
      <Divider />
    <Form form={updateForm} component={false}>
      <Table
      components={{
        body: {
          cell: EditableCell,
        },
      }}
      bordered
      dataSource={data.slice((currentPage - 1) * pageSize, currentPage * pageSize)}
      columns={mergedColumns}
      rowClassName="editable-row"
      pagination={{
        total: data.length,
        current: currentPage,
        pageSize: pageSize,
        onChange: (page) => {
          setCurrentPage(page);
          cancel();
        },
      }}
    /> 
    </Form>
    </>
    
   
    
  );
};



EditableTable.displayName = 'EditableTable';
export default EditableTable;



